﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace TEST
{
    public partial class Form1 : Form
    {
        string connectionString;
        DataSet ds;
        SqlDataAdapter da;
        SqlConnection conn;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            loadData();
        }
        public void loadData()
        {
            connectionString = "Data Source=VANSONVINA-PC;Initial Catalog=Permission;Persist Security Info=True;User ID=sa;Password=123456";
            ds = new DataSet();
            string query = "SELECT * FROM GROUPS";
            try
            {
                conn = new SqlConnection(connectionString);
                da = new SqlDataAdapter(query, conn);
                //SqlCommand cmd = new SqlCommand(query, conn);
                //da = new SqlDataAdapter(cmd);
                da.Fill(ds, "Groups");
                //dataGridView1.DataSource = ds.Tables["Users"];
                (dataGridView1.Columns["GroupID"] as DataGridViewComboBoxColumn).DataSource = ds.Tables["Groups"];
                (dataGridView1.Columns["GroupID"] as DataGridViewComboBoxColumn).DisplayMember = "GroupName";
                (dataGridView1.Columns["GroupID"] as DataGridViewComboBoxColumn).ValueMember = "GroupID";

                //dataGridView1.DataSource = ds.Tables["Groups"];
                da.SelectCommand.CommandText = "SELECT * FROM USERS";
                da.Fill(ds, "Users");
                dataGridView1.DataSource = ds.Tables["Users"];
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
           
        }
        private void btnThoat_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("bạn chắc chứ", "Thông Báo", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) 
           {
               Dispose();
           }
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            conn.Open();
            //lay ID dong hien tai
            int currentIndex = dataGridView1.CurrentCell.RowIndex;
            //Lay UserID
            int userID = Convert.ToInt32(dataGridView1.Rows[currentIndex].Cells[0].Value.ToString());
            string deleteStr = "DELETE FROM USERS WHERE USERID = '" + userID + "'";
            SqlCommand deleteCmd = new SqlCommand(deleteStr, conn);
            deleteCmd.CommandType = CommandType.Text;
            deleteCmd.ExecuteNonQuery();
            conn.Close();

        }
    }
}
